//
//  ImageAiExt.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/9/26.
//

//图片识别
import Foundation
class ImageAiExt : BaseViewModel {
    static let instance = ImageAiExt()
    private let modeType = IAiModelType.image.rawValue
    private let tag = "aiImage"
    
    private func isContains(path: String) -> Bool {
        return false
    }
    
    private func getImageCache(path: String) -> String {
        return ""
    }
    
    private func saveImageCache(path: String, desc: String) {
        
    }
    
    func doAIImage(path:String,content: String, backup: Bool = false) async throws -> String {
        let bean = ImageAiBean()
        bean.path = path
        let list :[ImageAiBean] = [bean]
        let listImage =  try await doAIImage(list: list, content: content)
        return listImage[0].describe ?? ""
    }
    
    func doAIImage(list:[ImageAiBean],content: String, backup: Bool = false) async throws -> [ImageAiBean] {
        var errorApi = ""
        do {
            for bean in list {
                if (isContains(path: bean.path ?? "")) {
                    showLog(tag, "已有缓存")
                    bean.describe = getImageCache(path: bean.path ?? "")
                    bean.cache = true
                } else {
                    var replyStr : String = ""
                    if backup {
                        //启动备用方案
                        try await retry(maxRetries: 3, retryDelayMillis: 500) {
                            let aiModeBean = configManager.getConfig().getAiChatMode2(key: self.modeType)
                            errorApi = "\(aiModeBean.host ?? ""),\(aiModeBean.model ?? "")"
                            let bean = AIImageRequstBean(model: aiModeBean.model, content: content, url: bean.path ?? "")
                            showLog(self.tag, "请求AI：\(bean)")
                            let result = try await AiNetManager.shared.requestAI(host: aiModeBean.host, token: aiModeBean.token, jsonObject: bean, modeType: AIChatResultBean.self)
                            replyStr = result.getReplyStr()
                            showLog(self.tag, replyStr)
                        }
                    } else if AiCustomUtils.shared.isCustomAi(type: self.modeType) {
                        //自定义
                        try await retry(maxRetries: 3, retryDelayMillis: 500) {
                            let host = AiCustomUtils.shared.getCustomHost(type: self.modeType)
                            let token = AiCustomUtils.shared.getCustomToken(type: self.modeType)
                            let model = AiCustomUtils.shared.getCustomModel(type: self.modeType)
                            errorApi = "\(host),\(model)"
                            let bean = AIImageRequstBean(model: model, content: content, url: bean.path ?? "")
                            showLog(self.tag, "请求AI：\(bean)")
                            let result = try await AiNetManager.shared.requestAI(host: host, token: token, jsonObject: bean, modeType: AIChatResultBean.self)
                            replyStr = result.getReplyStr()
                            showLog(self.tag, replyStr)
                        }
                    } else {
                        //配置模型
                        try await retry(maxRetries: 1, retryDelayMillis: 500) {
                            let aiModeBean = configManager.getConfig().getAiChatMode(key: self.modeType)
                            errorApi = "\(aiModeBean.host ?? ""),\(aiModeBean.model ?? "")"
                            let bean = AIImageRequstBean(model: aiModeBean.model, content: content, url: bean.path ?? "")
                            showLog(self.tag, "请求AI：\(bean)")
                            let result = try await AiNetManager.shared.requestAI(host: aiModeBean.host, token: aiModeBean.token, jsonObject: bean, modeType: AIChatResultBean.self)
                            replyStr = result.getReplyStr()
                            showLog(self.tag, replyStr)
                        }
                    }
                    showLog(self.tag, "回复：\(replyStr)")
                    bean.describe = replyStr
                    saveImageCache(path: bean.path ?? "", desc: bean.describe ?? "")
                    if (!AiCustomUtils.shared.isCustomAi(type: modeType)) {
                        AiChatExt.deductAiChatCount(2)
                    }
                }
            }
        }  catch let error {
            let it = self.dealError(error)
            if ERROR.NET_ERRPR.rawValue == it.code {
                AiChatExt.reportError(
                    type: self.modeType,
                    typeName: "图片识别错误",
                    message: it.realMessage,
                    errorApi: errorApi)
                
                if let error = configManager.getConfig().getAiError(content: it.realMessage) {
                    showToast(error)
                }
            } else {
                //非自定义使用备用方案
                if !backup && !AiCustomUtils.shared.isCustomAi(type: self.modeType) {
                    showLog(self.tag, "图片识别使用备用方案")
                    return try await self.doAIImage(list: list, content: content, backup: true)
                }
            }
        }
        return list
    }
}
